import React, {PureComponent, Fragment} from 'react';
import moment from 'moment';
import {connect} from 'dva';
import {
  Button,
  Tooltip,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  DatePicker,
  Select,
  Drawer,
  Col,
  Tag
} from 'antd';
import MyPagination from '@/components/MyPagination';
import find from 'lodash/find'
import debounce from 'lodash/debounce'
import {ellipsis,afterCloseModal,DescriptionItem,todayLastSecond, transilateBinary, string2Obj} from '@/utils/utils';


const FormItem = Form.Item;


@connect(({device_data2, loading}) => ({
  device_data2,
  loading: loading.models.device_data2,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, {name: 'device_add_and_edit'}),
      showdelBtn: find(this.permissions, {name: 'device_delete'}),
      showPasswordBtn: find(this.permissions, {name: 'user_default_password_edit'}),
      user_password_reset: find(this.permissions, {name: 'user_password_reset'}),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
    };
  }


  componentDidMount() {
    this.changeTableY()
    const {dispatch} = this.props;
    const {
      device_data2: {pageLoaded, scrollData},
    } = this.props;
    console.log('pageLoaded', pageLoaded)
    const table = document.querySelector('.ant-table-body')
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0)

    } else {
      const {
        device_data2: {searchParams},
      } = this.props;
      console.log('searchParams', searchParams)
      dispatch({
        type: 'device_data2/fetch',
        payload: searchParams,
        callback: ()=> {
          const {dispatch} = this.props;
          dispatch({
            type: 'device_data2/changeLoaded',
          })
        }
      });
    }

    window.addEventListener('resize', this.resize)
    table.addEventListener('scroll', debounce(this.scroll, 150))
  }

  scroll = (e)=> {
    const {dispatch} = this.props;
    dispatch({
      type: 'device_data2/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop
      },
    })
  }

  resize = ()=> {
    this.changeTableY()
  }

  changeTableY = ()=> {
    this.setState({
      tableY: document.querySelector('.table-pagination').getBoundingClientRect().top -
      document.querySelector('.custom-small-table').getBoundingClientRect().top - 50
    })
  }

  componentWillUnmount() {
    console.log('componentWillUnmount')
    window.removeEventListener('resize', this.resize)
    const table = document.querySelector('.ant-table-body')
    table.removeEventListener('scroll', debounce(this.scroll, 300))
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values)
    const that = this;
    const {dispatch} = this.props;
    dispatch({
      type: 'device_data2/fetch',
      payload: {
        ...values,
      },
      callback () {
        console.log('handleSearch callback')
        if (cb) cb()
      }
    });
  }

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
      device_data2: {searchParams},
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
      <FormItem label={'开始时间'}>
          {getFieldDecorator('started_at', {
            initialValue: moment(searchParams.started_at),
          })(
            <DatePicker
              showTime
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD HH:mm:ss"
            />
          )}
        </FormItem>
        <FormItem label={'结束时间'}>
          {getFieldDecorator('ended_at', {
            initialValue: moment(searchParams.ended_at),
          })(
            <DatePicker
              showTime
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD HH:mm:ss"
            />
          )}
        </FormItem>
        <FormItem label={<span>
          设备ID&nbsp;
          <Tooltip title="需传递完整设备ID，非模糊匹配">
            <Icon type="question-circle-o" />
          </Tooltip>
        </span>}>
          {getFieldDecorator('device_id', {
            initialValue: searchParams.device_id,
          })(<Input style={{width:'170px'}} placeholder="请输入完整设备ID" />)}
        </FormItem>

        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={()=> {
            const {form} = this.props;
            form.validateFields((err, fieldsValue) => {
              if (err) return;

              this.handleSearch({
                page: 1,
                per_page: this.state.per_page,
                ...fieldsValue,
                started_at: moment(fieldsValue.started_at).format("YYYY-MM-DD HH:mm:ss"),
                ended_at: moment(fieldsValue.ended_at).format("YYYY-MM-DD HH:mm:ss"),
              })

            });
          }}
          >
            查询
          </Button>
          <Button style={{marginLeft: 8}} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>

        </FormItem>

      </Form>
    );
  }


  handleFormReset = () => {
    const {form} = this.props;
    form.resetFields();
    this.handleSearch({
      started_at:moment(new Date().getFullYear()+'-'+(parseInt(new  Date().getMonth())+1)+'-'+'01' , "YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss"),
      ended_at: todayLastSecond(),
      device_id:'',
      page: 1,
      per_page: 30,
    })
  }
  render() {
    const that=this;
    const {
      device_data2: {data, loading, meta, searchParams, selectedRowKeys},
    } = this.props;
    const columns = [
      {
        title: '创建时间',
        dataIndex: 'created_at',

        width: 160,
        render: (val, record)=> ellipsis(val, 150)
      },
     {
        title: '设备ID',
        width: 180,
        dataIndex: 'device_id',

        render: (val, record)=> 
           ellipsis(val, 180)

      },
      {
        title: '设备EUI',
        width: 140,
        dataIndex: 'dev_eui',
        render: (val, record)=>
          ellipsis(record.data.dev_eui, 140)
      },
      {
        title: '产品代码',
        width: 100,
        dataIndex: 'product_code',
        render: (val, record)=>
          ellipsis(record.data.product_code, 100)
      },

      {
        title: '硬件版本',
        width: 100,
        dataIndex: 'hardware_version',
        render: (val, record)=>
          ellipsis(record.data.hardware_version, 100)
      },
      {
        title: '软件版本',
        width: 100,
        dataIndex: 'software_version',
        render: (val, record)=>
          ellipsis(record.data.software_version, 100)
      },

      {
        title: "RSSI",
        width: 60,
        dataIndex: 'rssi',
        render: (val, record)=>
          ellipsis(record.data.rssi, 60)
      }
      ,

      {
        title: '重启原因',
        width: 100,
        dataIndex: 'restart_reason',
        render: (val, record)=>{
          let transData=transilateBinary(record.data[`restart_reason`],8);
          let arr=[];
          console.log('transData',transData)
          for(let i=0;i<transData.length;i++){
            if(i===0&&transData[i]==='1'){
              arr.push('0 N/A')
            }
            if(i===1&&transData[i]==='1'){
              arr.push('LP')
            }
            if(i===2&&transData[i]==='1'){
              arr.push('WWDG')
            }
            if(i===3&&transData[i]==='1'){
              arr.push('IWDG')
            }
            if(i===4&&transData[i]==='1'){
              arr.push('SOFT')
            }
            if(i===5&&transData[i]==='1'){
              arr.push('POR')
            }
            if(i===6&&transData[i]==='1'){
              arr.push('PIN')
            }
            if(i===7&&transData[i]==='1'){
              arr.push('OB')
            }
          }
          return arr.map((item,index)=>{
            return <Tag className={'sign'} color="#108ee9" key={index}>{item}</Tag>
          })
        }

      } ,
      {
        title: '故障标志',
        dataIndex: 'fault_sign',
        width: 100,
        render: (val, record)=>{
          let transData=transilateBinary(record.data[`fault_sign`]);
          let arr=[];
          console.log('transData',transData)
          for(let i=0;i<transData.length;i++){
            if(i===15&&transData[i]==='1'){
              arr.push('空管')
            }
            if(i===14&&transData[i]==='1'){
              arr.push('过温')
            }
            if(i===13&&transData[i]==='1'){
              arr.push('过流')
            }
            if(i===12&&transData[i]==='1'){
              arr.push('电池欠压')
            }
            if(i===11&&transData[i]==='1'){
              arr.push('反向流量')
            }
          }
          return arr.map((item,index)=>{
            return <Tag className={'sign'} color="#ff0000" key={index}>{item}</Tag>
          })
        }
      },
      {
        title: 'UTC',

        dataIndex: 'utc',
        render: (val, record)=>
          ellipsis(record.data[`utc`], 60)
      } ,
    ];
    const rowSelection = {
      columnWidth: 40,
      selectedRowKeys,
      columnTitle: ' ',
      onChange: (selectedRowKeys) => {
        this.props.dispatch({
          type: 'device_data2/changeSelectRow',
          payload: selectedRowKeys,
        })
      },
    };
    return <div className="custom-card">
      <div className="table-title">设备信息列表</div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>
        <Table
          style={{color: '#fff'}}
          className="custom-small-table"
          loading={loading}
          rowKey="id"
          dataSource={data}
          columns={columns}
          pagination={false}
          size="small"
          scroll={{x: 1150, y: this.state.tableY}}
          rowSelection={rowSelection}
          onRow={(record) => ({
            onClick: () => {
              this.props.dispatch({
                type: 'device_data2/selectRow',
                payload: record,
              })
            },
          })}
        />

      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{...searchParams}} meta={meta} handleSearch={this.handleSearch} />
      </div>

    </div>
  }
}

export default BasicList;
